<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket;
    //判断当前浏览器是否支持websocket
    if (window.WebSocket){
        socket = new WebSocket("ws://localhost:7000/hello");
        //== read0
        //ev 收到服务器的response
        socket.onmessage=function (ev) {
            let elementById = document.getElementById('responseText');
            elementById.value = elementById.value +"\n" + ev.data;
        }
        //连接开启
        socket.onopen = function (ev) {
            let elementById = document.getElementById('responseText');
            elementById.value = "连接服务器成功";
        }

        socket.onclose = function (ev) {
            let elementById = document.getElementById('responseText');
            elementById.value = elementById.value +"\n" +"连接关闭";
        }

        function send() {
            if (!window.socket){
                alert("socket 没有准备完毕")
                return;
            }
            if (socket.readyState==WebSocket.OPEN){
                let elementById = document.getElementById('requestText').value;
                socket.send(elementById);
                document.getElementById('requestText').value('');
            }
            else
            {
                alert("连接没有开启");
            }
        }
    }
    else {
        alert("当前浏览器不支持 websocket")
    }
</script>

<form onsubmit="return false">
    <textarea id="requestText" name="message" style="height: 300px; width: 500px"></textarea>
    <br>
    <input type="button" value="发送" onclick="send()">
    <br>
    <textarea id="responseText" name="message" style="height: 300px; width: 500px"></textarea>
    <br>
    <input type="button" value="清空内容" onclick="document.getElementById('responseText').value('')">
</form>
</body>
</html>
